package cn.gailvlun.gll.db;

import java.util.ArrayList;
import java.util.List;

import cn.gailvlun.gll.net.apartment.room.Task;
import cn.gailvlun.gll.util.IsEmpty;
import io.realm.Realm;
import io.realm.RealmConfiguration;
import io.realm.RealmResults;



public class TaskDb {
    private static TaskDb INSTANCE = null;

    private RealmConfiguration mConfig;
    private static int mUserId;

    private TaskDb(int userId) {
        mUserId = userId;
        mConfig = new RealmConfiguration.Builder().name("task-" + userId + ".realm")
                .modules(Realm.getDefaultModule(), new NetModule())
                .schemaVersion(5)
                .migration(new NetMigration())
                .build();
    }

    public TaskDb init(int userId) {
        INSTANCE = new TaskDb(userId);
        return INSTANCE;
    }

    public static TaskDb getInstance() {
        if (INSTANCE == null) {
            synchronized (TaskDb.class) {
                if (INSTANCE == null) {
                    INSTANCE = new TaskDb(mUserId);
                }
            }
        }
        return INSTANCE;
    }

    public void saveTasks(List<Task> tasks) {
        Realm realm = Realm.getInstance(mConfig);
        realm.beginTransaction();
        realm.insert(tasks);
        realm.commitTransaction();
        realm.close();
    }

    public void setTasks(List<Task> tasks) {
        Realm realm = Realm.getInstance(mConfig);
        realm.beginTransaction();
        realm.delete(Task.class);
        realm.insert(tasks);
        realm.commitTransaction();
        realm.close();
    }

    public List<Task> getTasks() {
        Realm realm = Realm.getInstance(mConfig);
        return new ArrayList<>(realm.where(Task.class)
                .findAll());
    }

    public List<Task> getTasksById(ArrayList<Integer> idList) {
        Realm realm = Realm.getInstance(mConfig);
        RealmResults<Task> realmResults = realm.where(Task.class)
                .in("id", idList.toArray(new Integer[idList.size()]))
                .findAll();
        if (!IsEmpty.list(realmResults)) {
            ArrayList<Task> arrayList = new ArrayList<>();
            for (Integer taskId :
                    idList) {
                for (Task task: realmResults) {
                    if (taskId.equals(task.getId())) {
                        arrayList.add(task);
                        break;
                    }
                }
            }
            return arrayList;
        }

        return null;
    }

    public Task getTaskById(Integer taskId) {
        Realm realm = Realm.getInstance(mConfig);
        return realm.where(Task.class)
                .equalTo("id", taskId)
                .findFirst();
    }

}
